package config

import "fmt"

type IConfig interface {
	Load(file string) (ConfData, error)
	Parse(data []byte) (ConfData, error)
}

type ConfData interface {
	GetString(key string, defVal ...string) string
	GetInt(key string, defVal ...int) int
	GetInt64(key string, defVal ...int64) int64
	GetBool(key string) (bool, error)
	GetFloat64(key string, defVal ...float64) float64
	GetRawValue(key string) interface{}
	SetRawValue(key string, val interface{})
	ForEachKey(fn func(string, interface{}))
	ReplaceData(data map[string]interface{})
	SaveFile(dist string) error
}

var adapters = make(map[string]IConfig)

func Register(adapterName string, adapter IConfig) {
	if adapterName != "" && adapter != nil {
		if _, ok := adapters[adapterName]; !ok {
			adapters[adapterName] = adapter
		}
	}
}

func ConfFromFile(adapterName, file string) (ConfData, error) {
	if adapter, ok := adapters[adapterName]; ok {
		return adapter.Load(file)
	}
	return nil, fmt.Errorf("[Config] unknown adapter name %q", adapterName)
}

func ConfFromData(adapterName string, data []byte) (ConfData, error) {
	if adapter, ok := adapters[adapterName]; ok {
		return adapter.Parse(data)
	}
	return nil, fmt.Errorf("[Config] unknown adapter name %q", adapterName)
}
